package com.nx.platform.es.biz.query.search.handler;

import com.google.common.collect.Table;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.biz.query.search.SearchRequestContext;
import com.nx.platform.es.bean.dto.ESQueryConfDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.common.Strings;
import org.elasticsearch.search.sort.SortOrder;

import java.util.List;
import java.util.Map;

/**
 * @author
 * @since 2016年12月1日
 */
public enum SearchSortHandler implements SearchRequestHandler {

    INSTANCE;

    @Override
    public void handle(SearchRequestContext context) {
        Table<String, StatementOperator, List<String>> queryTable = context.getQueryTable();
        List<String> strategyA = queryTable.get("sort", StatementOperator.EQUAL);
        String strategy = null;
        if (CollectionUtils.isNotEmpty(strategyA)) {
            strategy = strategyA.get(0);
        }
        SortOrder sortOrder = null;
        Map<String, ESQueryConfDTO.OrderStrategy> orderMap = context.getConfig().getOrderStrategys();
        if (orderMap == null || orderMap.isEmpty()) {
            return;
        }
        ESQueryConfDTO.OrderStrategy order = null;
        if (!Strings.isNullOrEmpty(strategy)) {
            if (strategy.endsWith("_asc") || strategy.endsWith("_ASC")) {
                strategy = strategy.substring(0, strategy.length() - "_asc".length());
                sortOrder = SortOrder.ASC;
            } else if (strategy.endsWith("_desc") || strategy.endsWith("_DESC")) {
                strategy = strategy.substring(0, strategy.length() - "_desc".length());
                sortOrder = SortOrder.DESC;
            }
            order = orderMap.get(strategy);
        }
        if (order == null) {
            strategy = "default";
            order = orderMap.get(strategy);
        }
        if (order != null) {
            context.setParamFields(order.getParamFields());
            context.setSortFields(order.getSortFields());
            context.setScoreFunctionFields(order.getScoreFunctionFields());
            context.setRescoreFields(order.getRescoreFields());
            context.setSortOrder(sortOrder);
            context.setBoostMode(order.getBoostMode());
            context.setScoreMode(order.getScoreMode());
            context.setGeohashLevel(order.getGeohashLevel());
            context.setExpireAfterWrite(order.getExpireAfterWrite());
            context.setUseRequestCache(order.isUseRequestCache());
        }
        context.getTrace().append("&sort=").append(strategy).append("^").append(sortOrder);
    }

}
